package com.jse.web;

import java.lang.reflect.Method;
import java.util.function.Function;

import com.jse.anno.RequestMapping;

public class JavaRoute implements Route {

    private String method;
    private String path;
    private boolean regex;
    private Class<?> clazz;
    private Function<Ctx, Object> fun;
    private Method m;

    public JavaRoute(String path, Class<?> clazz, Method m) {
        this.path = path;
        this.clazz = clazz;
        this.m = m;
        init();
    }

    private void init() {
        if (Router.PATH_MATCHER.isPattern(path)) {
            regex = true;
        }
        var rm = m.getDeclaredAnnotation(RequestMapping.class);
        if (rm != null) {
            method = rm.method();
        }
        fun = createMethodInvoker();
    }

    private Function<Ctx, Object> createMethodInvoker() {
        return (Ctx c) -> {
            try {
                m.setAccessible(true);
                return m.invoke(null, c); // 注意: 这里假设方法不需要实例，如果是实例方法，需要传递实例对象。
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        };
    }

    @Override
    public String path() {
        return path;
    }

    public JavaRoute path(String path) {
        this.path = path;
        if (Router.PATH_MATCHER.isPattern(path)) {
            regex = true;
        }
        return this;
    }

    public JavaRoute method(String method) {
        this.method = method;
        return this;
    }

    @Override
    public Object run(Ctx c) {
        return fun.apply(c);
    }
}